import axios from 'axios';
import router from '../../router';
import { useLoadingStore } from '@/stores/loading';
import { baseUrl } from './env';

/**
 * 增强版 POST 请求函数
 * 支持自定义 headers 和 withCredentials 配置
 */
export default (
    url = '',
    data = {},
    successCallback = () => {},
    failCallback = () => {},
    config = {
        method: 'post',
        withCredentials: true  // 默认携带 Cookie
    }
) => {
    console.log("调用 post 方法，URL:", baseUrl + url, "参数:", data);

    const loadingStore = useLoadingStore();
    loadingStore.setSpinning(true);

    // 合并请求配置
    const axiosConfig = {
        ...config,

        withCredentials: config.withCredentials !== undefined ? config.withCredentials : true
    };

    axios.post(baseUrl + url, data, axiosConfig)
        .then(response => {
            handleResponse(response, successCallback, failCallback, loadingStore);
        })
        .catch(error => {
            handleError(error, failCallback, loadingStore);
        });
};

// 公共响应处理逻辑
function handleResponse(response, success, fail, loadingStore) {
    loadingStore.setSpinning(false);
    console.log("隐藏加载动画");

    if (response.status === 200) {
        console.log("成功回调");
        success?.(response.data);
    } else {
        fail?.(response.data);
    }
}

// 公共错误处理逻辑
function handleError(error, fail, loadingStore) {
    console.error("请求失败:", error);
    loadingStore.setSpinning(false);

    const statusCode = error.response?.status;
    if (statusCode === 401) {
        router.push({ name: 'Login' });
    } else {
        fail?.(statusCode);
    }
}